/*
 * @Description: 命令选项卡
 * @version: 1.0.0
 * @Author: YinJianFeng
 * @Date: 2024-08-25 13:33:45
 */
import React, { ReactNode, useContext, useEffect, useState } from 'react';
import { StyledTabPanel, StyledTabs } from './styled';
import { useCommandManager, CMEVENTS, Ctx2Context } from '@amcax/base';
import classNames from 'classnames';

export type CmdTabItem = {
  id: string;
  label: string;
  children: ReactNode;
};

interface IProps {
  frozenIds?: string[];
  items: CmdTabItem[];
  onTabSwitch?: (itemId: string) => void | boolean | Promise<void | boolean>;
}

export const CmdTabs = (props: IProps) => {
  const { userEvents } = useContext(Ctx2Context);

  const [freezedTabIds, setFreezedTabIds] = useState<string[]>([]);
  const { resetCmd } = useCommandManager();
  const [activeTabId, setActiveTabId] = useState('');

  const { frozenIds, items, onTabSwitch = () => resetCmd() } = props;

  useEffect(() => {
    registerEvents();
    setActiveTabId(items[0].id);
    if (frozenIds) {
      setFreezedTabIds(frozenIds);
    } else {
      // 默认冻结第一个Tab
      setFreezedTabIds([items[0].id]);
    }
    return () => {
      unregisterEvents();
    };
  }, []);

  const registerEvents = () => {
    userEvents.on(CMEVENTS.CMD_TABS_ACTIVE, (tabId: string) => {
      setActiveTabId(tabId);
    });
  };
  const unregisterEvents = () => {
    userEvents.off(CMEVENTS.CMD_TABS_ACTIVE);
  };

  const isFreezedTab = (tabId: string) => {
    return freezedTabIds.includes(tabId);
  };
  const freezeTab = (tabId: string) => {
    setFreezedTabIds([...freezedTabIds, tabId]);
  };
  const unfreezeTab = (tabId: string) => {
    setFreezedTabIds(freezedTabIds.filter((id) => id !== tabId));
  };

  const tabs = (
    <ul>
      {items.map((item, index) => (
        <li
          key={item.id}
          className={classNames(
            `${activeTabId === item.id ? 'active' : ''}`,
            'whitespace-nowrap',
          )}
          onClick={async () => {
            const onSwitch = await onTabSwitch(item.id);
            if (onSwitch !== false) {
              setActiveTabId(item.id);
            }
          }}
          onDoubleClick={() => {
            if (isFreezedTab(item.id)) {
              unfreezeTab(item.id);
            } else {
              freezeTab(item.id);
            }
          }}
        >
          {isFreezedTab(item.id) ? (
            <i className={index === 0 ? 'freeze rounded' : 'freeze'}></i>
          ) : null}
          {item.label}
        </li>
      ))}
    </ul>
  );

  const tabsPanel = (
    <div>
      {items.map((item) => (
        <React.Fragment key={item.id}>
          {item.id === activeTabId || isFreezedTab(item.id)
            ? item.children
            : null}
        </React.Fragment>
      ))}
    </div>
  );

  return (
    <StyledTabs>
      {tabs}
      <StyledTabPanel>{tabsPanel}</StyledTabPanel>
    </StyledTabs>
  );
};
